//
//  PictureSelectorViewController.swift
//  Sina
//
//  Created by 王杰 on 15/11/27.
//  Copyright © 2015年 王杰. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let colum:CGFloat = 4
private let pictureMargin: CGFloat = 10
private let maxImageCount = 3

class PictureSelectorViewController: UICollectionViewController {
    //添加图片数组属性
     lazy var imageList = [UIImage]()
    
    init() {
    
        let layout = UICollectionViewFlowLayout()
        let w = (screenW - (colum + 1) * pictureMargin) / colum
        layout.itemSize = CGSize(width: w, height: w)
        
        layout.minimumInteritemSpacing = pictureMargin
        layout.minimumLineSpacing = pictureMargin
        layout.sectionInset = UIEdgeInsetsMake(pictureMargin, pictureMargin, 0, pictureMargin)
        
        super.init(collectionViewLayout: layout)
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

   
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let delta = (imageList.count == maxImageCount) ? 0 : 1

        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
    
        cell.backgroundColor = UIColor.randomColor()
        cell.selectorCellDelegate = self
        
        if indexPath.item == imageList.count {
        
        cell.image = nil
        
        }else {
        
        cell.image = imageList[indexPath.item]
            
        }
        return cell
    }

    override func prefersStatusBarHidden() -> Bool {
        
        return true
    }
}
extension PictureSelectorViewController: PictureSelectorCellDelegate {
    
    func userWillAddPicture(cell:PictureSelectorCell) {
        if  cell.image != nil {
        
            print("已经添加图片")
            return
        }
        
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    func userwillDeletePicture(cell:PictureSelectorCell) {
        print("删除图片")
        
        let indexPath = collectionView?.indexPathForCell(cell)
        
        self.imageList.removeAtIndex(indexPath!.item)
        
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            cell.alpha = 0
            }) { (_) -> Void in
                cell.alpha = 1

                self.collectionView?.reloadData()
        }
    }
    
}
extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        print(image)
//        print(editingInfo)
        //刷新集合视图
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
        
    }

}
//协议方法
@objc protocol PictureSelectorCellDelegate:NSObjectProtocol {
    
    optional func userWillAddPicture(cell:PictureSelectorCell)
    
    optional func userwillDeletePicture(cell:PictureSelectorCell)

}
class PictureSelectorCell: UICollectionViewCell {
    
    weak var selectorCellDelegate:PictureSelectorCellDelegate?
    
    @objc private func addPicture() {
    
    selectorCellDelegate?.userWillAddPicture?(self)
    
    }
    @objc private func deletePicture() {
    
    selectorCellDelegate?.userwillDeletePicture?(self)
    }
    
    //定义图片数据模型
    var image:UIImage? {
    
        didSet{
        
            deleteBtn.hidden = (image == nil)
            if image != nil {
            
            addBtn.setBackgroundImage(image, forState: .Normal)
            } else {
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }

        }
    }
    //设置frame
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置UI
    private func setupUI() {
    
    contentView.addSubview(addBtn)
    contentView.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
            
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deletePicture", forControlEvents: .TouchUpInside)
        
    }
    //懒加载控件
    private lazy var addBtn: UIButton = UIButton(title: nil
        , backImage: "compose_pic_add", color: nil)
    
    private lazy var deleteBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)

}
























